'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import AppHeader from '@/components/ui/app-header';
import { useSession } from 'next-auth/react';
import { projectApi } from '@/lib/api';

export default function NewProjectPage() {
  const router = useRouter();
  const { data: session, status } = useSession();
  const [formData, setFormData] = useState({
    name: '',
    description: '',
    status: 'planning',  // 添加默认状态
  });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  // 如果未登录，重定向到登录页
  if (status === 'unauthenticated') {
    router.push('/auth/login');
    return null;
  }

  // 处理表单字段变更
  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  // 处理表单提交
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError('');

    try {
      // 确保表单数据完整
      if (!formData.name.trim()) {
        throw new Error('项目名称不能为空');
      }

      // 添加用户ID和时间戳
      const projectData = {
        ...formData,
        ownerId: session?.user?.id,  // 当前用户作为项目拥有者
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
      };

      console.log('创建项目数据:', projectData);
      
      // 调用真实的API
      const response = await projectApi.createProject(projectData);
      
      console.log('项目创建响应:', response);
      
      if (!response || (response && !response.success && !response.id)) {
        throw new Error(response?.message || '创建项目失败，请重试');
      }
      
      // 创建成功，等待一小段时间确保数据更新
      await new Promise(resolve => setTimeout(resolve, 500));
      
      // 重定向到项目列表页
      router.push('/project');
      
      // 强制刷新，确保获取最新数据
      router.refresh();
      
    } catch (err: any) {
      console.error('创建项目失败:', err);
      setError(err.message || '创建项目失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen">
      <main className="py-6 px-4 sm:px-6 lg:px-8 max-w-7xl mx-auto">
        <AppHeader
          title="创建新项目"
          subtitle="填写项目信息开始协作"
        />
        
        <div className="mt-8">
          <div className="bg-white shadow sm:rounded-lg">
            <form onSubmit={handleSubmit} className="p-6">
              {error && (
                <div className="mb-4 p-4 bg-red-50 border-l-4 border-red-500 text-red-700">
                  <p>{error}</p>
                </div>
              )}
              
              <div className="space-y-6">
                <div>
                  <label htmlFor="name" className="block text-sm font-medium text-gray-700">
                    项目名称 <span className="text-red-500">*</span>
                  </label>
                  <div className="mt-1">
                    <input
                      type="text"
                      name="name"
                      id="name"
                      value={formData.name}
                      onChange={handleChange}
                      required
                      className="input w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
                      placeholder="输入项目名称"
                    />
                  </div>
                </div>
                
                <div>
                  <label htmlFor="description" className="block text-sm font-medium text-gray-700">
                    项目描述
                  </label>
                  <div className="mt-1">
                    <textarea
                      name="description"
                      id="description"
                      value={formData.description}
                      onChange={handleChange}
                      rows={4}
                      className="input w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
                      placeholder="描述项目的目标和内容（可选）"
                    />
                  </div>
                </div>
                
                <div>
                  <label htmlFor="status" className="block text-sm font-medium text-gray-700">
                    项目状态
                  </label>
                  <div className="mt-1">
                    <select
                      name="status"
                      id="status"
                      value={formData.status}
                      onChange={handleChange}
                      className="input w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
                    >
                      <option value="planning">规划中</option>
                      <option value="in-progress">进行中</option>
                      <option value="completed">已完成</option>
                    </select>
                  </div>
                </div>
                
                <div className="flex justify-end">
                  <button
                    type="button"
                    onClick={() => router.back()}
                    className="mr-4 inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md shadow-sm text-gray-700 bg-white hover:bg-gray-50 focus:outline-none"
                  >
                    取消
                  </button>
                  <button
                    type="submit"
                    disabled={loading || !formData.name.trim()}
                    className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-[var(--primary-color)] hover:bg-[var(--primary-hover)] focus:outline-none disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    {loading ? '创建中...' : '创建项目'}
                  </button>
                </div>
              </div>
            </form>
          </div>
        </div>
      </main>
    </div>
  );
} 